package keepaliveddeploylogic

import (
	"context"
	"os"
	"yunzhan/common/utils"

	"yunzhan/rpc-server/internal/svc"
	agent "yunzhan/rpc-server/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ModifyKeepalivedConfLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewModifyKeepalivedConfLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyKeepalivedConfLogic {
	return &ModifyKeepalivedConfLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ModifyKeepalivedConfLogic) ModifyKeepalivedConf(in *agent.ModifyKeepalivedConfRequest) (*agent.BaseKeepalivedConfResponse, error) {

	if in.Content == "" {
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "Content cannot be empty",
		}, nil
	}

	// keepalived.conf 文件路径
	filePath := "/usr/local/keepalived-2.3.1/etc/keepalived.conf"
	backupFilePath := "/usr/local/keepalived-2.3.1/etc/keepalived.conf.bak"

	// 备份当前的 keepalived.conf 文件
	err := os.Rename(filePath, backupFilePath)
	if err != nil {
		logx.Errorf("Failed to backup keepalived.conf file: %v", err)
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "备份keepalived.conf配置文件失败",
		}, err
	}

	// 保存新的 keepalived.conf 内容
	err = os.WriteFile(filePath, []byte(in.Content), 0644)
	if err != nil {
		// 恢复备份
		os.Rename(backupFilePath, filePath)
		logx.Errorf("Failed to write new keepalived.conf file: %v", err)
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "更新keepalived.conf配置文件失败",
		}, err
	}

	output, err := utils.ExecCommand("sudo systemctl reload keepalived.service")
	if err != nil {
		// 恢复备份
		os.Rename(backupFilePath, filePath)
		logx.Errorf("Failed to reload keepalived config: %v, output: %s", err, output)
		return &agent.BaseKeepalivedConfResponse{
			Code:    500,
			Message: "Failed to reload keepalived config",
		}, err
	}

	return &agent.BaseKeepalivedConfResponse{
		Code:    200,
		Message: "Success",
	}, nil
}
